#!/usr/bin/python3
# @author Loganli
# Gitee: https://gitee.com/attacker
# Description: Zabbix告警推送至飞书，支持状态智能着色与内容紧凑美化
import sys
import requests
import re

def get_template_color(subject):
    # 智能着色：红=告警，绿=恢复，灰=其它
    if re.search(r'(PROBLEM|Problem:)', subject, re.IGNORECASE):
        return "red"
    elif re.search(r'(OK|Resolved)', subject, re.IGNORECASE):
        return "green"
    else:
        return "grey"

def send_lark_alert(webhook_token, subject, message):
    webhook_url = f"https://open.larksuite.com/open-apis/bot/v2/hook/{webhook_token}"
    # 内容紧凑：去除多余换行，统一格式
    msg_lines = [line.strip() for line in message.split('\n') if line.strip()]
    compact_msg = '\n'.join(msg_lines)
    card_content = {
        "msg_type": "interactive",
        "card": {
            "header": {
                "title": {
                    "tag": "plain_text",
                    "content": subject
                },
                "template": get_template_color(subject)
            },
            "elements": [
                {
                    "tag": "div",
                    "text": {
                        "tag": "lark_md",
                        "content": compact_msg
                    }
                },
                {
                    "tag": "note",
                    "elements": [
                        {
                            "tag": "plain_text",
                            "content": "Zabbix监控告警通知"
                        }
                    ]
                }
            ]
        }
    }
    try:
        response = requests.post(webhook_url, json=card_content)
        response.raise_for_status()
        print(f"飞书消息已发送至Webhook {webhook_token}")
        return True
    except Exception as e:
        print(f"飞书推送失败: {str(e)}")
        return False

if __name__ == "__main__":
    if len(sys.argv) != 4:
        print("Usage: zabbix-lark-alart.py <webhook_token> <subject> <message>")
        sys.exit(1)
    _, sendto, subject, message = sys.argv
    send_lark_alert(sendto, subject, message)